package com.ruoyi.utils;

import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
public class WeiteTxtFileUtils<E> {


    public void add(String fileName, String fileHeader, List<E> fileBody) throws ClassNotFoundException {
        if (fileBody == null || fileBody.size() == 0) {

            return;
        }
        File file = new File(fileName);
        try (

                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8));
        ) {
            bufferedWriter.write(fileHeader + "^");
            for (E o : fileBody) {
                ReflectionUtils.nullifyStrings(o);
                if (fileBody.size() - 1 == fileBody.indexOf(o)) {
                    bufferedWriter.write(o.toString() + "^]]]");
                } else {
                    bufferedWriter.write(o.toString() + "^");

                }

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    public void urlVerifyAndAdd(String url, String fileName, String fileHeader, List<E> fileBody) {
        File file = new File(url);
        try {
            if (!file.exists()) {
                if (file.mkdirs()) {
                    System.out.println("创建目录");
                    add(fileName, fileHeader, fileBody);
                } else {
                    System.out.println("chuan失败");
                }
            } else {
                add(fileName, fileHeader, fileBody);
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

}
